package com.example.jisuanqi;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class MainActivity extends AppCompatActivity {

    private TextView displayTextView;
    private TextView historyTextView;
    private String currentNumber = "";
    private String operator = "";
    private double firstNumber = 0;
    private StringBuilder inputBuilder = new StringBuilder();
    private List<String> historyList = new ArrayList<>();
    private boolean isResultDisplayed = false;

    private Button leftParenthesisButton;
    private Button rightParenthesisButton;
    private Button dotButton;
    private Button deleteButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        displayTextView = findViewById(R.id.displayTextView);
        historyTextView = findViewById(R.id.historyTextView);

        // 设置数字按钮点击事件
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            Button numberButton = findViewById(getResources().getIdentifier("button" + i, "id", getPackageName()));
            numberButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isResultDisplayed) {
                        // 如果是在结果显示后首次输入数字，清空相关状态并重新构建输入
                        currentNumber = String.valueOf(finalI);
                        inputBuilder = new StringBuilder(String.valueOf(finalI));
                        isResultDisplayed = false;
                    } else {
                        currentNumber += finalI;
                        inputBuilder.append(finalI);
                    }
                    displayTextView.setText(inputBuilder.toString());
                }
            });
        }

        // 设置运算符按钮点击事件
        Button addButton = findViewById(R.id.addButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputBuilder.append(" + ");
                performOperation();
                operator = "+";
                currentNumber = "";
                displayTextView.setText(inputBuilder.toString());
            }
        });

        Button subtractButton = findViewById(R.id.subtractButton);
        subtractButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputBuilder.append(" - ");
                performOperation();
                operator = "-";
                currentNumber = "";
                displayTextView.setText(inputBuilder.toString());
            }
        });

        Button multiplyButton = findViewById(R.id.multiplyButton);
        multiplyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputBuilder.append(" * ");
                performOperation();
                operator = "*";
                currentNumber = "";
                displayTextView.setText(inputBuilder.toString());
            }
        });

        Button divideButton = findViewById(R.id.divideButton);
        divideButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputBuilder.append(" / ");
                performOperation();
                operator = "/";
                currentNumber = "";
                displayTextView.setText(inputBuilder.toString());
            }
        });

        // 设置等号按钮点击事件
        Button equalButton = findViewById(R.id.equalButton);
        equalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performOperation();
                operator = "";
                currentNumber = "";
                double result = firstNumber;
                // 保存原始输入用于历史记录
                StringBuilder originalInput = new StringBuilder(inputBuilder);
                currentNumber = String.valueOf(result);
                inputBuilder = new StringBuilder(currentNumber);
                displayTextView.setText(String.valueOf(result));
                // 将原始输入和结果添加到历史记录
                historyList.add(originalInput.toString() + " = " + result);
                updateHistory();
                isResultDisplayed = true;
            }
        });

        // 设置清除按钮点击事件
        Button clearButton = findViewById(R.id.clearButton);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentNumber = "";
                operator = "";
                firstNumber = 0;
                inputBuilder = new StringBuilder();
                displayTextView.setText("");
                isResultDisplayed = false;
            }
        });

        // 设置 ( 按钮点击事件
        leftParenthesisButton = findViewById(R.id.leftParenthesisButton);
        leftParenthesisButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputBuilder.append(" ( ");
                displayTextView.setText(inputBuilder.toString());
            }
        });

        // 设置 ) 按钮点击事件
        rightParenthesisButton = findViewById(R.id.rightParenthesisButton);
        rightParenthesisButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputBuilder.append(" ) ");
                displayTextView.setText(inputBuilder.toString());
            }
        });

        // 设置. 按钮点击事件
        dotButton = findViewById(R.id.dotButton);
        dotButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isResultDisplayed) {
                    currentNumber = "0.";
                    inputBuilder = new StringBuilder("0.");
                    isResultDisplayed = false;
                } else {
                    if (!currentNumber.contains(".")) {
                        currentNumber += ".";
                        inputBuilder.append(".");
                    }
                }
                displayTextView.setText(inputBuilder.toString());
            }
        });

        // 设置delete按钮点击事件
        deleteButton = findViewById(R.id.deleteButton);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputBuilder.length() > 0) {
                    inputBuilder.deleteCharAt(inputBuilder.length() - 1);
                    if (inputBuilder.toString().endsWith(" ")) {
                        inputBuilder.delete(inputBuilder.length() - 3, inputBuilder.length());
                        operator = "";
                    }
                    displayTextView.setText(inputBuilder.toString());
                    if (inputBuilder.length() == 0) {
                        currentNumber = "";
                        isResultDisplayed = false;
                    } else {
                        if (inputBuilder.toString().matches("^\\d+$")) {
                            currentNumber = inputBuilder.toString();
                        } else {
                            String[] parts = inputBuilder.toString().split(" ");
                            currentNumber = parts[parts.length - 1];
                        }
                    }
                }
            }
        });
    }

    private void performOperation() {
        Stack<Double> numberStack = new Stack<>();
        Stack<String> operatorStack = new Stack<>();

        String input = inputBuilder.toString();
        if (!input.matches("^\\d+(\\.\\d+)?(\\s*[+\\-*/\\(\\)]\\s*\\d+(\\.\\d+)?)*$")) {
            displayTextView.setText("Error: Invalid input");
            return;
        }
        String[] parts = input.split(" ");
        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];
            if (part.matches("^\\d+(\\.\\d+)?$")) {
                numberStack.push(Double.parseDouble(part));
            } else if (part.equals("(")) {
                operatorStack.push(part);
            } else if (part.equals(")")) {
                while (!operatorStack.peek().equals("(")) {
                    double secondNumber = numberStack.pop();
                    double firstNumber = numberStack.pop();
                    String op = operatorStack.pop();
                    double result = calculate(firstNumber, op, secondNumber);
                    numberStack.push(result);
                }
                operatorStack.pop();// 弹出'('
            } else {
                while (!operatorStack.empty() && hasLowerOrEqualPriority(part, operatorStack.peek())) {
                    double secondNumber = numberStack.pop();
                    double firstNumber = numberStack.pop();
                    String op = operatorStack.pop();
                    double result = calculate(firstNumber, op, secondNumber);
                    numberStack.push(result);
                }
                operatorStack.push(part);
            }
        }
        while (!operatorStack.empty()) {
            double secondNumber = numberStack.pop();
            double firstNumber = numberStack.pop();
            String op = operatorStack.pop();
            double result = calculate(firstNumber, op, secondNumber);
            numberStack.push(result);
        }
        firstNumber = numberStack.pop();
    }

    private double calculate(double first, String operator, double          second) {
        switch (operator) {
            case "+":
                return first + second;
            case "-":
                return first - second;
            case "*":
                return first * second;
            case "/":
                if (second!= 0) {
                    return first / second;
                } else {
                    displayTextView.setText("Error: Division by zero");
                    return 0;
                }
            default:
                return 0;
        }
    }

    private boolean hasLowerOrEqualPriority(String op1, String op2) {
        if ((op1.equals("+") || op1.equals("-")) && (op2.equals("*") || op2.equals("/"))) {
            return false;
        }
        return true;
    }

    private void updateHistory() {
        StringBuilder historyText = new StringBuilder();
        if (historyList.size() > 5) {
            historyList.remove(0);
        }
        for (String historyItem : historyList) {
            historyText.append(historyItem).append("\n");
        }
        historyTextView.setText(historyText.toString());
    }
}